package com.shoulder.ssh.utils;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ExecUtils extends SSHUtils {

    private ChannelExec channelExec;

    private void initChannelExec(Session session) throws Exception {
        // 打开执行shell指令的通道
        channelExec = (ChannelExec) session.openChannel("exec");
    }

    public String execCmd(String command,Session session) throws Exception {
        initChannelExec(session);
        channelExec.setCommand(command);
        channelExec.connect();
        StringBuilder sb = new StringBuilder(16);
        try (InputStream in = channelExec.getInputStream();
             InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(isr)) {
            String buffer;
            while ((buffer = reader.readLine()) != null) {
                sb.append(buffer).append("\n");
            }
            log.info("execCmd result - > {}", sb);
            channelExec.disconnect();
            return sb.toString();
        }
    }

}
